<script setup>
import {ref, defineProps, defineEmits, watch, onMounted, reactive} from 'vue'
import { ElMessage,ElMessageBox  } from 'element-plus';
import AddressDialog from "@/components/AddressDialog.vue";
import axios from 'axios'
const addressId = ref(0)   //要提交的收货地址，也是默认选中的地址
const addresses = ref([])  //显示地址列表
const cart = ref({})
const dialogVisible = ref(false)
const showAddressDialog = ()=>{
  dialogVisible.value = true
}

const formEdit = ref({})

const provinces = ref([])
const cities = ref([])
const districts = ref([])
const initProvinceData = () => {
  axios.get('/china/getAllProvince').then(response => {
    provinces.value = response.data;
    console.log("初始化的省",provinces.value)
  });
}
// 根据省份获取城市列表，并设置为市级 el-select 的 options
const handleProvinceChange = ()=>{
  axios.get('/address/getAllCities', {
    params: {"provinceId": formEdit.value.province}
  }).then((response) => {//成功回调函数
    cities.value = response.data;
  }).catch((error) => {
    console.log(error);
  });
  //清空之前的数据
  districts.value = []
  formEdit.value.city = ''
  formEdit.value.district = ''
}
// 根据城市获取区县列表，并设置为区级 el-select 的 options
const handleCityChange = ()=>{
  axios.get('/address/getAllDistricts', {
    params: {"cityId": formEdit.value.city}
  }).then((response) => {//成功回调函数
    districts.value = response.data;
  }).catch((error) => {
    console.log(error);
  });
  formEdit.value.district = ''
}

const visible4Edit=ref(false);
const cancelEdit=()=>{
  visible4Edit.value = false;
  refFormEdit.value.resetFields();
}//编辑弹窗内的取消按钮
const handleEdit = (row)=>{
  let json = JSON.stringify(row);
  console.log(json);
  formEdit.value = JSON.parse(json);
  axios.get('/address/getAllCities', {
    params: {"provinceId": formEdit.value.province}
  }).then((response) => {//成功回调函数
    cities.value = response.data;
  })
  axios.get('/address/getAllDistricts', {
    params: {"cityId": formEdit.value.city}
  }).then((response) => {//成功回调函数
    districts.value = response.data;
  })
  visible4Edit.value = true;

}
const edit=()=> {
  refFormEdit.value.validate((valid) => {
    if (valid) {
      axios.put(`/address/edit`, formEdit.value)
          .then(resp => {
            initAddressData();
            visible4Edit.value = false;
            ElMessage({type: 'success', message: '编辑成功',})
          }).catch(error => {
            console.log(error);
            ElMessage({type: 'error', message: '编辑失败',})
      });
    }else {
      ElMessage.error('表单验证失败')
      return false;
    }
  })
}

//关闭对话框
const handleAddClose = (val)=> {
  //修改外部的值
  dialogVisible.value = val;
}
//后端查询所有收货地址
const initAddressData = ()=> {
  //后端查询所有收货地址
  axios.get('/address/findAddress').then(resp=> {
    addresses.value = resp.data;
    console.log("所有收货地址",addresses.value)
    addresses.value.forEach(e => {
      if (e.isDefault == 1) {
        addressId.value = e.id;
      }
    });
  });
}

const handleDelete = (row) => {
  console.log("删除按钮传递的id", row.id)
  ElMessageBox.confirm(
      `您确定要删除地址【${row.allAddress}】吗？`, '警告',
      {
        confirmButtonText: '确 认',
        cancelButtonText: '取 消',
        type: 'warning',
      }
  ).then(() => {
    return axios.delete(`/address/remove/${row.id}`);
  }).then(() => {
    ElMessage({type: 'success', message: '删除成功', showClose: true})
    initAddressData();
  }).catch(errorMsg => {
    if (errorMsg == 'cancel')
      return;
    ElMessage({type: 'info', message: errorMsg,})
  })
}
const setDefault = (row)=>{
  let json = JSON.stringify(row);
  console.log(json);
  formEdit.value = JSON.parse(json);
  formEdit.value.isDefault=1
  axios.put(`/address/edit`, formEdit.value)
      .then(resp => {
        initAddressData();
        ElMessage({type: 'success', message: '修改默认成功',})
      }).catch(error => error);
}
const rowClassName = ({ row }) => {
  if (row.isDefault === 1) {
    return 'default-address';
  }
  return '';
};

const refFormEdit = ref(null); // 初始化验证
const rules = reactive({
  province: [
    { required: true, message: '请输入省', trigger: 'blur' }
  ],
  city: [
    { required: true, message: '请输入市', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '请输入区', trigger: 'blur' }
  ],
  detailAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  telephone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    { min: 11, max: 11, message: '长度必须是11位', trigger: 'blur' }
  ],
  receiver: [
    { required: true, message: '请输入收货人', trigger: 'blur' }
  ],
});

onMounted(()=>{
  initAddressData()
  initProvinceData()
})
</script>

<template>
  <el-card>
    收货地址
    <el-button style="margin-left: 10px;"
               type="success" @click="showAddressDialog"
               size="large">新增收货地址
    </el-button>
    <!--数据显示-->
    <template v-if="addresses.length > 0">
      <el-table :data="addresses" style="width: 100%"
                stripe highlight-current-row class="addr-table" >
        <el-table-column type="index" width="55" label="序号">
          <template #default="{$index}">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="receiver" label="收件人" width="100">
          <template #default="{row}">{{ row.receiver }}</template>
        </el-table-column>
        <el-table-column prop="telephone" label="手机号码" width="150">
          <template #default="{row}">{{ row.telephone}}</template>
        </el-table-column>
        <el-table-column prop="allAddress" label="完整地址" width="350">
          <template #default="{row}">{{ row.allAddress }}</template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{row}">
            <el-button type="warning" size="small" @click="handleEdit(row)">修改</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column label="移动设置" width="150" >
          <template #default="{row}" >
            <el-button @click="setDefault(row)" :class="row.isDefault === 1 ? 'default-button' : ''">设为默认</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <div><!-- 修改收货地址 -->
      <el-dialog title="修改收货地址" width="580px" v-model="visible4Edit">
        <el-form label-width="80px" :model="formEdit" size="small" :rules="rules" ref="refFormEdit">
          <el-row>
            <el-col :span="8">
              <el-form-item label="省" prop="province">
                <el-select v-model="formEdit.province" @change="handleProvinceChange"
                           style="width: 110px">
                  <el-option
                      v-for="province in provinces"
                      :key="province.id"
                      :label="province.name"
                      :value="province.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="市" prop="city">
                <el-select
                    v-model="formEdit.city"  @change="handleCityChange"
                    style="width: 110px">
                  <el-option
                      v-for="city in cities"
                      :key="city.id"
                      :label="city.name"
                      :value="city.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="区" prop="area">
                <el-select v-model="formEdit.area" style="width: 120px">
                  <el-option
                      v-for="district in districts"
                      :key="district.id"
                      :label="district.name"
                      :value="district.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="详细地址" prop="detailAddress">
            <el-input type="textarea"
                      v-model="formEdit.detailAddress"
                      style="width: 438px">
            </el-input>
          </el-form-item>
          <el-row>
            <el-col :span="11">
              <el-form-item label="手机号码" prop="telephone">
                <el-input v-model="formEdit.telephone"
                          style="width: 175px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="收件人" prop="receiver">
                <el-input v-model="formEdit.receiver"
                          style="width:190px"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="默认地址">
            <el-switch v-model="formEdit.isDefault" active-text="是"
                       inactive-text="否"
                       :active-value="1"
                       :inactive-value="0"
                       active-color="#13ce66" inactive-color="#ff4949">
            </el-switch>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
                <el-button @click="cancelEdit">
                    取消</el-button>
                <el-button type="primary"
                           @click="edit">确定</el-button>
        </span>
      </el-dialog>
    </div>

    <!-- 新增收货地址 -->
    <AddressDialog :dialogVisible="dialogVisible" @reload-address="initAddressData"
                    @close="handleAddClose"/>


  </el-card>
</template>

<style scoped>
.addr-table {
  border-radius: 10px;
}
.default-button {
  color: #b94242; /* 设置按钮文字颜色 */
  font-weight: bold; /* 加粗字体 */
}
</style>